﻿#include "LcdUtorrentApplication.h"

#include <QtCore/QDebug>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QMetaEnum>
#include <QtCore/QMetaObject>
#include <QtCore/QSettings>

LcdUtorrentApplication::LcdUtorrentApplication(int argc, char *argv[])
	: QCoreApplication(argc,argv)
{
	firstLine=0;
	firstLineColor=0;
	exitCode=0;
	max_dl_rate=0;
	max_ul_rate=0;

	QSettings settings("LcdUtorrent.ini",QSettings::IniFormat);
	settings.beginGroup("LcdUtorrent");
	QString title = settings.value("title","Lcd Utorrent").toString();
	bool repeate = settings.value("repeate",false).toBool();
	int refresh = settings.value("refresh",1000).toInt();
	max_dl_rate_after_0 = settings.value("max_dl_rate_after_0",2000).toInt();
	max_ul_rate_after_0 = settings.value("max_ul_rate_after_0",100).toInt();
	button_increment_up = settings.value("button_increment_up",5).toInt();
	button_increment_down = settings.value("button_increment_down",100).toInt();
	settings.endGroup();
	settings.beginGroup("Serveur");
	QString serveur = settings.value("serveur","127.0.0.1").toString();
	QString port = settings.value("port","8080").toString();
	QString user = settings.value("user","admin").toString();
	QString password = settings.value("password","admin").toString();
	settings.endGroup();


	uApi = new UtorrentApi(0,serveur,port,user,password);
	connect(uApi, SIGNAL(resultReceive(QString,QJsonDocument)), this, SLOT(resultReceive(QString,QJsonDocument)));
	connect(uApi, SIGNAL(errorReceive(QString,int,QNetworkReply::NetworkError,QString)), this, SLOT(errorReceive(QString,int,QNetworkReply::NetworkError,QString)));

	lcd = new LogiLcd(title);
	lcd->repeate=repeate;
	connect(lcd, SIGNAL(buttonPressed(int)), this, SLOT(buttonPressed(int)));

	timer = new QTimer();
	timer->setInterval(refresh);
	connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
	timer->start();

	updateScreen();
}

LcdUtorrentApplication::~LcdUtorrentApplication()
{
	shutdown();
}
void LcdUtorrentApplication::shutdown()
{
	if(lcd!=NULL)
	{
		disconnect(lcd, SIGNAL(buttonPressed(int)), this, SLOT(buttonPressed(int)));
		delete lcd;
	}
	lcd=NULL;
}

void LcdUtorrentApplication::timeout()
{
	uApi->getSettings();
	uApi->getList();
}

void LcdUtorrentApplication::buttonPressed(int button)
{
	if(button!=0)
	{
		if(button & LOGI_LCD_MONO_BUTTON_0)
		{
			max_ul_rate-=button_increment_up;
			if(max_ul_rate<0)
				max_ul_rate=max_ul_rate_after_0;
			uApi->setSetting("max_ul_rate",QString("%1").arg(max_ul_rate));
		}
		else if(button & LOGI_LCD_MONO_BUTTON_1)
		{
			max_ul_rate+=button_increment_up;
			uApi->setSetting("max_ul_rate",QString("%1").arg(max_ul_rate));
		}
		if(button & LOGI_LCD_MONO_BUTTON_2)
		{
			max_dl_rate-=button_increment_down;
			if(max_dl_rate<0)
				max_dl_rate=max_dl_rate_after_0;
			uApi->setSetting("max_dl_rate",QString("%1").arg(max_dl_rate));
		}
		else if(button & LOGI_LCD_MONO_BUTTON_3)
		{
			max_dl_rate+=button_increment_down;
			uApi->setSetting("max_dl_rate",QString("%1").arg(max_dl_rate));
		}
	}
}

void LcdUtorrentApplication::updateScreen()
{

	if(list.contains("build"))
	{
		lcd->SetMonoText(0,QString::fromLatin1("µtorrent %1").arg(list.take("build").toInt()));
		lcd->SetColorTitle(QString::fromLatin1("µtorrent %1").arg(list.take("build").toInt()));
	}

	int sizeUp=1;
	int sizeDown=1;
	int upload=0;
	int download=0;
	QString addUp;
	QString addDown;

	if(list.contains("torrents"))
	{
		QJsonArray torrents = list.take("torrents").toArray();
		for(int i=0;i<torrents.size();++i)
		{
			QJsonArray torrent = torrents.at(i).toArray();
			/*int status = torrent.at(1).toInt();
			1 = Started (Démarré)
			2 = Checking (Vérification)
			4 = Start after check (Démarrer après vérification)
			8 = Checked (Vérifié)
			16 = Error (Erreur)
			32 = Paused (Suspendu)
			64 = Queued (Mis en file d'attente)
			128 = Loaded (Chargé)*/
			upload += torrent.at(8).toInt();
			download += torrent.at(9).toInt();
		}
		upload/=1000;
		download/=1000;

		if(upload>9)
			++sizeUp;
		if(upload>99)
			++sizeUp;
		if(download>9)
			++sizeDown;
		if(download>99)
			++sizeDown;
		if(sizeUp==1)
			addUp="  ";
		else if(sizeUp==2)
			addUp=" ";
		if(sizeDown==1)
			addDown="  ";
		else if(sizeDown==2)
			addDown=" ";

		lcd->SetMonoText(1,QString("Cur Up:%1%2Kio, Down:%3%4Kio").arg(addUp).arg(upload).arg(addDown).arg(download));
	}

	if(settings.contains("settings"))
	{
		QJsonArray settings2 = settings.take("settings").toArray();
		sizeUp=1;
		sizeDown=1;
		QString max_dl_rate("0");
		QString max_ul_rate("0");
		for(int i=0;i<settings2.size();++i)
		{
			QJsonArray setting = settings2.at(i).toArray();
			if(setting.at(0).toString()=="max_dl_rate")
				max_dl_rate = setting.at(2).toString();
			else if(setting.at(0).toString()=="max_ul_rate")
				max_ul_rate = setting.at(2).toString();
		}
		this->max_dl_rate=max_dl_rate.toInt();
		this->max_ul_rate=max_ul_rate.toInt();

		sizeUp=max_ul_rate.length();
		sizeDown=max_dl_rate.length();
		addUp="";
		if(sizeUp==1)
			addUp="  ";
		else if(sizeUp==2)
			addUp=" ";
		addDown="";
		if(sizeDown==1)
			addDown="  ";
		else if(sizeDown==2)
			addDown=" ";

		lcd->SetMonoText(2,QString("Max Up:%1%2Kio, Down:%3%4Kio").arg(addUp).arg(max_ul_rate).arg(addDown).arg(max_dl_rate));

	}


	lcd->SetMonoText(LOGI_LCD_MONO_MAX_LINE,"  <  Up  >      < Down >");
	lcd->SetColorText(LOGI_LCD_COLOR_MAX_LINE,"TODO");
}

void LcdUtorrentApplication::resultReceive(QString request,QJsonDocument result)
{
	if(request=="LIST")
	{
		list = result.object();
		updateScreen();
	}
	else if(request=="GETSETTINGS")
	{
		settings = result.object();
		updateScreen();
	}
	else if(request=="SETSETTING")
	{
		uApi->getSettings();
	}

}

void LcdUtorrentApplication::errorReceive(QString demande,int statusCodeV,QNetworkReply::NetworkError error,QString errorString)
{
	qDebug()<<demande<<" "<<statusCodeV;
	qDebug()<<error<<" "<<errorString;

	lcd->SetMonoText(0,QString::fromLatin1("µtorrent"));

	QMetaObject metaObject = QNetworkReply::staticMetaObject;
	QMetaEnum metaEnum = metaObject.enumerator( metaObject.indexOfEnumerator( "NetworkError" ) );
	QString errorMsg = metaEnum.valueToKey(error);

	lcd->SetMonoText(1,QString("%1 : %2").arg(statusCodeV).arg(errorMsg));

	switch(error)
	{
	case QNetworkReply::UnknownContentError://webui désactivé
		lcd->SetMonoText(2,QString::fromLatin1("Vous devez activer WebUI"));
		break;
	case QNetworkReply::ConnectionRefusedError://utorrent coupé
		lcd->SetMonoText(2,QString::fromLatin1("Vous devez lancer µtorrent"));
		break;
	case QNetworkReply::AuthenticationRequiredError://mauvais mdp
		lcd->SetMonoText(2,QString::fromLatin1("Mauvais authentification"));
		break;
	default:
		lcd->SetMonoText(2,"");
		break;
	}
	lcd->SetMonoText(3,errorString);
}